﻿/**
 * 粘帖图片到编辑器
 */
(function(E){
var Consts = E.consts, Event = E.mod('Event');

if( !window.FileReader ){
	return;
}

// html5 粘帖剪切板图片到编辑器
// 火狐下不需要特殊处理，图片可以直接粘帖到编辑器
// chrome浏览器需要添加这个事件
if($.browser.webkit){
	Event.bind('paste', function(dom, e){
		if( !e ){ return; }
		var clipboardData = e.originalEvent.clipboardData,
			items = clipboardData.items,
			item = items[0];
		
		if( item.kind=='file' && item.type.match(/^image\//i) ){
			var imagefile = item.getAsFile(),
				reader = new FileReader();
				
			reader.onload = function( ev ){
				var sHtml='<img src="'+ev.target.result+'"/>';
				E.pasteHTML(sHtml);
			}
			reader.readAsDataURL(imagefile);
			return false;
		}
	});
}
// 拖拽图片文件到编辑器区域，触发上传

if ( !window.XMLHttpRequest ){
	return;
}

Event.bind('dragenter', function(dom, e){
	
});

Event.bind('dragover', function(dom, e){
	var DragImage = E.plugin("DragImage");
	if( DragImage && DragImage.mousedown ){
		// 什么也不做
	}else{
		e.stopPropagation();
		e.preventDefault();
	}
});

Event.bind('drop', function(dom, e){
	if( !e.originalEvent.dataTransfer.files.length ){
		return;
	}
	var images = [],
		plugin = E.plugin('AjaxUpload'),
		mainAjax = MainAjaxUpload,
		Client = {
			event: e,
			action: 'upload.php?action=saveFromDrag',
			inputName: 'filedata',
			init: function( fileList ){
				var plugin = E.clickPlugin('AjaxUpload');
				plugin.initFileList( fileList , plugin);
			},
			onprogress: function( progress ){
				plugin.update( plugin, progress );
			},
			
			callback: function( nextfile , data ){
				var panel = plugin.panel;
				if( typeof data === 'object' && data.success ){
					images.push( data.url );
				}
				if(typeof nextfile === 'object') {
					panel.find('.jqe-panel-noewUploadName').html(nextfile.fileName);
				}
			},
			
			// 上传完成，将图片插入到编辑器
			oncomplete: function(){
				var html = [],
					panel = plugin.panel,
					totalProgress = panel.find('.jqe-panel-totalprogress'),
					uploadName = panel.find('.jqe-panel-noewUploadName'),
					currentProgress = panel.find('.jqe-panel-currentprogress'),
					successFileList = mainAjax.successFileList,
					fileItem = successFileList[successFileList.length-1],
					fileSize = mainAjax.formatBytes(fileItem.fileSize);
				for( var i in images ){
					html.push('<img src="'+ images[i] +'" style="max-width:600px;" />');
				}
				E.pasteHTML( html.join('<p>&nbsp;</p>') );
				totalProgress.html( '100%('+mainAjax.totalCount+'/'+mainAjax.totalCount+')' );
				currentProgress.html( '100%('+fileSize+'/'+fileSize+')');
				uploadName.html(fileItem.fileName);
				plugin.unlock();
				setTimeout(function(){
					E.hidePlugin('AjaxUpload');
				},3000);
			}
		};
	mainAjax.ondrop( Client );
});

Event.bind('dragleave', function(dom, e){
	
});

E.plugin('AjaxUpload', {
	config:{
		width: 400,
		height: 80,
		position: 'center',
		overlay: true
	},
	style : '.jqe-plugin-AjaxUpload{font-size:15px;font-weight:bold;line-height:25px;}\
			.jqe-plugin-AjaxUpload span{width:100px;text-align:right;float:left;}\
			.jqe-plugin-AjaxUpload div{display:inline-block;color:red;margin-left:10px;overflow:hidden;height:25px;width:250px;}',
	init: function( self ){
		var html = [];
		html.push('<div class="jqe-plugin-AjaxUpload"><span>总进度：</span>');
		html.push('<div class="jqe-panel-totalprogress"></div>');
		html.push('<br><span>当前进度：</span>');
		html.push('<div class="jqe-panel-currentprogress"></div>');
		html.push('<br><span>当前文件名：</span><div class="jqe-panel-noewUploadName"></div>');
		html.push('</div>');
		self.cache['html'] = html.join('');
	},
	
	callback : function(panel , self) {
		self.lock();
	},
	onClose : function(panel , self) {
		self.unlock();
	},
	// 构造上传文件的可视列表
	initFileList: function( fileList , self){
		var panel = self.panel,
			mainAjax = MainAjaxUpload,
			fileItem = fileList[0],
			totalProgress = panel.find('.jqe-panel-totalprogress'),
			uploadName = panel.find('.jqe-panel-noewUploadName'),
			currentProgress = panel.find('.jqe-panel-currentprogress');
		totalProgress.html( '0%(0/'+mainAjax.totalCount+')' );
		currentProgress.html( '0%(0/'+mainAjax.formatBytes(fileItem.fileSize)+')');
		uploadName.html(fileItem.fileName);
	},
	
	// 更新进度条
	update: function( self, progress ){
		var panel = self.panel,
			o = progress,
			totalProgress = panel.find('.jqe-panel-totalprogress'),
			uploadName = panel.find('.jqe-panel-noewUploadName'),
			currentProgress = panel.find('.jqe-panel-currentprogress');
		totalProgress.html( o.totalPercent+'%('+o.completeCount +'/'+o.totalCount+')' );
		currentProgress.html( ''+o.currentPercent+'%('+o.loaded+'/'+o.fileSize+')');
		//uploadName.html(o.fileName);
	}
});

// ajax 上传对象
var MainAjaxUpload = {
	xhr: new XMLHttpRequest(),
	
	// 调用者
	Client: null,
	
	// 已经完成上传的文件数
	completeCount: 0,
	
	// 所有文件的总数
	totalCount: 0,
	
	// 所有文件的总大小
	totalSize: 0,
	
	// 上传完成的文件总大小，默认值是1
	completeSize: 1,
	
	//是否正在上传图片
	isUploading: false,
	
	// 待上传的文件列表
	fileList: [],
	
	// 上传成功的文件列表
	successFileList: [],
	
	// 上传失败的文件列表
	failureFileList: [],
	
	// 初始化
	init: function( fileList ){
		if( this.isUploading ){
			return;
		}
		
		var self = this;
		self.completeCount = 1;
		//self.totalSize = 0;
		//self.completeSize = 0;
		
		self.fileList = fileList;
		self.successFileList = [];
		self.failureFileList = [];
		self.isUploading = true;
		self.totalCount = fileList.length;
		self.start( );
	},
	
	/**
	* @param {Object} Client 客户-使用者
	*/
	ondrop: function( Client ){
		var self = this,
			dataTransfer = Client.event.originalEvent.dataTransfer,
			fileList = [],
			files = dataTransfer.files;
			
		self.Client = Client;
		Client.event.stopPropagation();
		Client.event.preventDefault();
		
		for(var i=0, len = files.length; i<len; i++){
			fileList.push( files[i] );
			self.totalSize += files[i].fileSize;
		}
		
		if( fileList.length ){
			Client.init( fileList );
			self.init(fileList);
		}
	},
	
	// 开始上传
	start: function( ){
		var self = this,
			fileList = self.fileList,
			file = fileList.shift();
			
		if( file ){
			self.post( file );
		}else{
			// 所有文件上传完成
			self.complete();
		}
	},
	
	// 所有文件上传完成
	complete: function( ){
		var self = this;
		//setTimeout(function(){
			self.Client.oncomplete( );
			self.isUploading = false;
		//}, 1000);
	},
	
	// 每个文件上传完毕后调用
	callback: function( file, responseText ){
		var self = this, data;
		self.completeCount += 1;
		self.completeSize += file.fileSize;
		
		try{
			data = $.parseJSON(responseText);
			
		}catch(ex){};
		
		self.Client.callback( self.fileList[0],data );
	},
	
	// 显示进度条
	onprogress: function( ev, file ){
		var self = this;
		if( ev && ev.loaded >= 0 ) {
			var currentPercent = Math.round( (ev.loaded * 100)/ file.fileSize ),
				totalPercent = Math.round( ((ev.loaded + self.completeSize) * 100) / self.totalSize );
			var progress = {
				totalPercent: totalPercent, // 总进度百分数
				currentPercent: currentPercent, //当前文件进度百分数
				loaded: self.formatBytes(ev.loaded), //当前上传的块大小
				fileSize: self.formatBytes(file.fileSize), //当前上传的文件大小
				fileName: file.fileName, //当前上传的文件名称
				
				//当前已经上传完成的总大小
				completeSize: self.formatBytes(ev.loaded + self.completeSize), 
				totalSize: self.formatBytes(self.totalSize), //所有文件总大小
				completeCount: self.completeCount, //正在上传第几个文件
				totalCount: self.totalCount //总文件数
			};
			self.Client.onprogress( progress );
		} else {
			//不支持进度
			
		}
	},
	
	// 使用ajax方式向服务器发送文件
	// 每次发送一个文件
	post: function( file ){
		var self = this, xhr = self.xhr;
		xhr.onreadystatechange = function(){
			if(xhr.readyState === 4){
				if( xhr.status == 200 ){
					// 上传成功
					self.successFileList.push( file );
					self.callback( file, xhr.responseText );
					// 继续下一个文件上传
					self.start();
				}else{
					// 上传错误
					self.failureFileList.push( file );
				}
			}
		};
		
		if( xhr.upload ){
			xhr.upload.onprogress = function( ev ){
				self.onprogress( ev, file );
			};
		}else{
			self.onprogress( false ); //不支持进度
		}
		
		xhr.open("POST", self.Client.action);
		xhr.setRequestHeader('Content-Type', 'application/octet-stream');
		xhr.setRequestHeader('Content-Disposition', 'attachment; name="'+self.Client.inputName+'"; filename="'+file.fileName+'"');
		
		if( xhr.sendAsBinary ){
			// Firefox 支持 sendAsBinary() 和 send() 方法
			// sendAsBinary() 不是标准方法，只能在firefox3.6+当中使用
			xhr.sendAsBinary( file.getAsBinary() );
		}else{
			// 2011-07-21
			// Chrome 浏览器不支持sendAsBinary方法，使用send()方法
			xhr.send(file);
		}
	},
	
	formatBytes: function(bytes) {
		var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
		var e = Math.floor(Math.log(bytes)/Math.log(1024));
		return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+s[e];
	}
}

})(jQEditor);